package com.wjerp.tplus.server.common.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.UUID;

/**
 * 实现web 访问返回日志记录
 * @author lishuailei
 */
@Aspect
@Component
public class WebLogAspect {
    public static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    public static ThreadLocal<String> threadLocal = new ThreadLocal<>();

    /**
     * 定义一个切入点
     */
    @Pointcut("execution(public * com.wjerp.tplus.server.api.controller..*.*(..))")
    public void method(){
        threadLocal.set(UUID.randomUUID().toString());
    }

    /**
     * 方法进入
     */
    @Before("method()")
    public void doBefore(JoinPoint joinPoint){
        // 接收到请求，记录请求内容
        logger.info("WebLogAspect.doBefore()" + threadLocal.get()+ " ********************************");
        writeRequestInfo(joinPoint);
        //获取所有参数方法一：
//        Enumeration<String> enu=request.getParameterNames();`
//        while(enu.hasMoreElements()){
//            String paraName=(String)enu.nextElement();
//            System.out.println(paraName+": "+request.getParameter(paraName));
//        }
    }

    @AfterReturning(value = "method()",returning = "response")
    public void  doAfterReturning(JoinPoint joinPoint, Object response){
        // 处理完请求，返回内容
        logger.info("WebLogAspect.doAfterReturning()" + threadLocal.get()+ "  ****************************");
        writeRequestInfo(joinPoint);
        logger.info("response : " + response);
    }

    @AfterThrowing(value = "method()", throwing = "exception")
    public void wrapException(JoinPoint joinPoint, RuntimeException exception) {
        // 处理完请求，返回内容
        logger.info("WebLogAspect.doAfterReturning() " + threadLocal.get()+ " ****************************");
        writeRequestInfo(joinPoint);
        logger.error("exception : " + exception.getMessage());
    }

    void writeRequestInfo(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        logger.info("UUID:" + threadLocal.get());
        // 记录下请求内容
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

    }

}
